package com.jmebananas.game.tile;

import java.awt.Point;
import java.awt.Rectangle;

import javacream.scene.sprite.Sprite;
import javacream.scene.sprite.SpriteFrame;

/**
 * SpriteTile
 *
 * @author Glenn Powell
 *
 */
public class SpriteTile extends Tile {

	private static final long serialVersionUID = 1L;
	
	
	protected Sprite sprite = null;
	
	protected SpriteFrame lastFrame = null;

	
	public SpriteTile(String name) {
		this(name, null, true);
	}
	
	public SpriteTile(String name, boolean animates) {
		this(name, null, animates);
	}

	public SpriteTile(String name, Sprite sprite) {
		this(name, sprite, true);
	}

	public SpriteTile(String name, Sprite sprite, boolean animates) {
		super(name);
		
		setSprite(sprite);
		
		if (animates) {
			SpriteTileController controller = new SpriteTileController(this);
			addController(controller);
		}
	}
	
	public Sprite getSprite() {
		return sprite;
	}
	
	public void setSprite(Sprite sprite) {
		this.sprite = sprite;
		setImage(sprite.getImage(), false);
	}
	
	public void update(float dt) {
		if (sprite != null) {
			sprite.update(dt);
	
			SpriteFrame frame = sprite.getCurrentFrame();
			if (frame != lastFrame) {
				if (frame != null) {
					Rectangle bounds = frame.getBounds();
					setSize(bounds.width, bounds.height);
					
					Point anchor = frame.getAnchor();
					setAnchor(anchor.x, anchor.y);
					
					setSubimageBound(bounds);
				}
				lastFrame = frame;
			}
		}
	}

}
